﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 角色控制类
/// 1.控制角色移动
/// 2.调用摄像机跟随
/// 3.实现FingerGestures插件类相关委托
/// </summary>
public class RoleCtrl : MonoBehaviour {

    private Vector3 m_TargetPos = Vector3.zero;             //鼠标点击碰撞点
    [SerializeField]
    private float m_Speed = 10f;                            //角色移动速度
    [SerializeField]
    private float m_RotationSpeed = 0.2f;                   //角色转身速度
    private Quaternion m_TargetQuaternion;                  //角色转身的方向
    private bool m_RotationOver = false;                    //角色转身是否完成
    private CharacterController m_CharacterController;      //角色控制器

    void Start()
    {
        //角色控制器赋值
        this.m_CharacterController = this.GetComponent<CharacterController>();

        //初始化镜头
        if (CameraCtrl.Instance != null){ CameraCtrl.Instance.Init(); }

        //手指滑动委托
        FingerEvent.Instance.OnFingerDrag += OnFingerDrag;

        //手指点击委托
        FingerEvent.Instance.OnPlayerClickGround += OnPlayerClickGround;
    }

    void FixedUpdate()
    {
        //移动角色
        MoveRole();

        //摄像机跟随主角
        CameraAutoFollow();
    }

    void Update()
    {
        //TODO
    }

    #region 移动角色
    private void MoveRole()
    {
        if (m_CharacterController == null) return;

        //角色着地
        if (!m_CharacterController.isGrounded)
        {
            m_CharacterController.Move(this.transform.position + new Vector3(0, -1000, 0) - this.transform.position);
        }

        //Debug.DrawLine(Camera.main.transform.position, m_TargetPos);

        //角色移动
        if (m_TargetPos != Vector3.zero)
        {
            if (Vector3.Distance(m_TargetPos, this.transform.position) > 0.1f)
            {
                Vector3 direction = (m_TargetPos - this.transform.position).normalized * Time.deltaTime * m_Speed;
                direction.y = 0;
                this.transform.LookAt(new Vector3(m_TargetPos.x, this.transform.position.y, m_TargetPos.z));

                //角色缓慢转身（方式1）
                //if (m_RotationSpeed <= 1)
                //{
                //    m_RotationSpeed += 5f * Time.deltaTime;
                //    m_TargetQuaternion = Quaternion.LookRotation(direction, Vector3.up);
                //    this.transform.rotation = Quaternion.Lerp(this.transform.rotation, m_TargetQuaternion, m_RotationSpeed);
                //}

                //角色缓慢转身（方式2）
                //if (!m_RotationOver)
                //{
                //    m_RotationSpeed += 5f;
                //    m_TargetQuaternion = Quaternion.LookRotation(direction);
                //    this.transform.rotation = Quaternion.Lerp(this.transform.rotation, m_TargetQuaternion, m_RotationSpeed);

                //    if (Quaternion.Angle(m_TargetQuaternion, this.transform.rotation) < 1f)
                //    {
                //        m_RotationSpeed = 1;
                //        m_RotationOver = true;
                //    }
                //}

                m_CharacterController.Move(direction);
            }
        }
    }

    #endregion

    #region 摄像机跟随角色
    private void CameraAutoFollow()
    {
        if (CameraCtrl.Instance == null) return;
        CameraCtrl.Instance.transform.position = this.gameObject.transform.position;
        CameraCtrl.Instance.AutoLookAt(gameObject.transform.position);

        //用键盘测试
        //if (Input.GetKey(KeyCode.A))
        //{
        //    CameraCtrl.Instance.SetCameraRotate(0);
        //}
        //else if (Input.GetKey(KeyCode.D))
        //{
        //    CameraCtrl.Instance.SetCameraRotate(1);
        //}
        //else if (Input.GetKey(KeyCode.W))
        //{
        //    CameraCtrl.Instance.SetCameraUpAndDown(0);
        //}
        //else if (Input.GetKey(KeyCode.S))
        //{
        //    CameraCtrl.Instance.SetCameraUpAndDown(1);
        //}
        //else if (Input.GetKey(KeyCode.I))
        //{
        //    CameraCtrl.Instance.SetCameraZoom(0);
        //}
        //else if (Input.GetKey(KeyCode.L))
        //{
        //    CameraCtrl.Instance.SetCameraZoom(1);
        //}
    }

    #endregion

    #region 手指滑动点击相关委托
    //手指滑动时执行
    private void OnFingerDrag(FingerEvent.FingerDir obj)
    {
        switch (obj)
        {
            //手指滑动控制上下左右
            case FingerEvent.FingerDir.Left:
                CameraCtrl.Instance.SetCameraRotate(0);
                break;
            case FingerEvent.FingerDir.Right:
                CameraCtrl.Instance.SetCameraRotate(1);
                break;
            case FingerEvent.FingerDir.Up:
                CameraCtrl.Instance.SetCameraUpAndDown(1);
                break;
            case FingerEvent.FingerDir.Down:
                CameraCtrl.Instance.SetCameraUpAndDown(0);
                break;

            //控制放缩TODO
        }
    }

    //手指点击时执行主角移动（注册委托）
    private void OnPlayerClickGround()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hitInfo;
        if (Physics.Raycast(ray, out hitInfo))
        {
            if (hitInfo.collider.gameObject.name.Equals("Ground", System.StringComparison.CurrentCultureIgnoreCase))
            {
                this.m_TargetPos = hitInfo.point;
                //Debug.Log(hitInfo.collider.gameObject.name);
            }
        }
    }

    #endregion

    #region 脚本销毁时调用
    void OnDestroy()
    {
        //移除时取消滑动监听
        FingerEvent.Instance.OnFingerDrag -= OnFingerDrag;

        //移除时取消点击监听
        FingerEvent.Instance.OnPlayerClickGround -= OnPlayerClickGround;

    }

    #endregion
}
